package com.shop.api;

import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.shop.config.R;
import com.shop.service.service.impl.SmsServiceImpl;
import com.shop.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

import static com.shop.utils.CommonMethod.checkPhone;

/*阿里云短信服务*/
@RestController
@RequestMapping("/sms")
@CrossOrigin  //跨域
@Slf4j
public class SmsController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SmsServiceImpl smsServiceImpl;

    //发送短信（商家注册的时候发送的短信）
    @GetMapping("/send/mer/{redisKey}/{phone}")
    public R sendMessage(@PathVariable String redisKey, @PathVariable String phone){
        log.info("==========================================");
        log.info("发送短信请求");
        log.info("==========================================");
        //校验手机号
        checkPhone(phone);
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        SendSmsResponseBody body = null;
        try {
            //调用阿里云短信服务
            body = smsServiceImpl.sendMessage(phone, code);
            if (!body.code.equals("OK")){
                return R.error("短信发送失败~"+body.getMessage());
            }
        } catch (Exception e) {
            log.info("短信发送异常:{}",e.getMessage());
            return R.error("短信发送失败，{}"+e.getMessage());
        }
        //储存短信到redis中
        redisTemplate.opsForValue().set(redisKey, code, 5, TimeUnit.MINUTES);
        System.out.println("验证码为： " + code);
        System.out.println("body.getMessage() = " + body.getMessage());
        //返回ok
        log.info("==========================================");
        log.info("发送短信请求完成");
        log.info("==========================================");
        return R.ok("短信发送成功");
    }

}
